<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Silence
 * Date: 3/8/12
 * Time: 3:51 AM
 * To change this template use File | Settings | File Templates.
 */

require_once('api.php');
require_once('constants.php');

$con = db_prepare();

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if (isset($_GET['item']) && ($_GET['item'] === 'read_sources')) {
            $data = get_sources();
            print json_encode($data);
        }
        break;
    case 'POST':
        // var_dump($_POST);
        // var_dump($_GET);
        if (isset($_GET['item']) && ($_GET['item'] === 'update_sources')) {
            $data = json_decode($HTTP_RAW_POST_DATA);
			$item = $data;
			print $data->id;
			$sql = "UPDATE `sources` SET `name` = '$item->name', `description` = '$item->description',
					`cost` = '$item->cost', `pid` = '$item->pid' WHERE `id` = $item->id";
			db_die($result = mysql_query($sql));
        }
		else if (isset($_GET['item']) && ($_GET['item'] === 'delete_sources')) {
            $data = json_decode($HTTP_RAW_POST_DATA);
            // check if it is an array
            if (is_array($data)) {
                foreach ($data as $item) {
                    $sql = "DELETE FROM `sources` WHERE `id` = $item->id";
                    db_die($result = mysql_query($sql));
                }
            }
            else {
                $sql = "DELETE FROM `sources` WHERE `id` = $data->id";
                db_die($result = mysql_query($sql));
            }
		}
		else if (isset($_GET['item']) && ($_GET['item'] === 'create_sources')) {
			$data = json_decode($HTTP_RAW_POST_DATA);
			$sql = "INSERT INTO `sources` (`cost`, `pid`) VALUES (0, $data->pid)";
			db_die($result = mysql_query($sql));
			$sql = "SELECT * FROM `sources` WHERE `cost` = 0";
			db_die($result = mysql_query($sql));
			$result = mysql_fetch_array($result);
			print json_encode(array('id' => $result['id'], 'cost' => $result['cost'], 'pid' => $result['pid'], 'success' => true));
			//print json_encode(array('source' => array('id' => $result['id']), 'success' => true));
		}
        break;
    default:
        break;
}


mysql_close($con);